<script setup>
import { ref, onMounted } from 'vue'
import { Modal, message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  getOrganizationList,
  getOrganizationOptions,
  createOrganization,
  updateOrganization,
  deleteOrganization,
} from '@/api/system'

const formRef = ref()
const visible = ref(false)
const editingRecord = ref(null)
const loading = ref(false)
const confirmLoading = ref(false)
const searchKeyword = ref('')
const formData = ref({
  code: '',
  name: '',
  level: '',
  parent: undefined,
  manager: '',
  date: null,
  status: '启用',
})

const columns = [
  { title: '机构编码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '机构名称', dataIndex: 'name', key: 'name', width: 200 },
  { title: '机构级别', dataIndex: 'level', key: 'level', width: 100 },
  { title: '上级机构', dataIndex: 'parentName', key: 'parent', width: 150 },
  { title: '负责人', dataIndex: 'manager', key: 'manager', width: 120 },
  { title: '成立日期', dataIndex: 'date', key: 'date', width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 150 },
]

const dataSource = ref([])
// 上级机构选项
const parentOptions = ref([])

// 获取机构列表
const fetchOrganizationList = async () => {
  loading.value = true
  try {
    const response = await getOrganizationList(searchKeyword.value || undefined)

    if (response && response.list) {
      // 扁平化机构列表（处理嵌套结构）
      const flattenOrganizations = (orgs) => {
        const result = []
        orgs.forEach((org) => {
          result.push({
            id: org.id,
            code: org.code,
            name: org.name,
            level: org.level,
            parent: org.parent || org.parentCode || null,
            parentName: org.parentName || '-',
            manager: org.manager || '',
            date: org.date || '',
            status: org.status || '启用',
            key: org.id,
          })
          if (org.children && org.children.length > 0) {
            result.push(...flattenOrganizations(org.children))
          }
        })
        return result
      }

      const flattenedList = flattenOrganizations(response.list)
      dataSource.value = flattenedList
    } else {
      dataSource.value = []
      parentOptions.value = []
    }
  } catch (error) {
    console.error('获取机构列表失败:', error)
    message.error('获取数据失败')
    dataSource.value = []
    parentOptions.value = []
  } finally {
    loading.value = false
  }
}

// 存储所有机构选项（用于筛选）
const allOrganizationOptions = ref([])

// 获取所有机构选项
const fetchAllOrganizationOptions = async () => {
  try {
    const response = await getOrganizationOptions()
    if (response && response.list) {
      allOrganizationOptions.value = response.list
    } else {
      allOrganizationOptions.value = []
    }
  } catch (error) {
    console.error('获取机构选项失败:', error)
    allOrganizationOptions.value = []
  }
}

// 根据机构级别筛选上级机构选项
const updateParentOptions = () => {
  const currentLevel = formData.value.level
  const currentCode = editingRecord.value?.code

  if (!currentLevel) {
    parentOptions.value = []
    return
  }

  // 一级机构：不能选择上级机构
  if (currentLevel === '一级机构') {
    parentOptions.value = []
    formData.value.parent = undefined
    return
  }

  // 二级机构：只能选择一级机构
  if (currentLevel === '二级机构') {
    const validOptions = allOrganizationOptions.value
      .filter((org) => {
        const isCurrentRecord = currentCode && org.value === currentCode
        return !isCurrentRecord && org.level === '一级机构'
      })
      .map((org) => ({
        value: org.value,
        label: org.label,
      }))
    parentOptions.value = validOptions

    // 如果当前选择的上级机构不在有效选项中，清空它
    if (formData.value.parent && !validOptions.find((opt) => opt.value === formData.value.parent)) {
      formData.value.parent = undefined
    }
    return
  }

  // 三级机构：只能选择二级机构
  if (currentLevel === '三级机构') {
    const validOptions = allOrganizationOptions.value
      .filter((org) => {
        const isCurrentRecord = currentCode && org.value === currentCode
        return !isCurrentRecord && org.level === '二级机构'
      })
      .map((org) => ({
        value: org.value,
        label: org.label,
      }))
    parentOptions.value = validOptions

    // 如果当前选择的上级机构不在有效选项中，清空它
    if (formData.value.parent && !validOptions.find((opt) => opt.value === formData.value.parent)) {
      formData.value.parent = undefined
    }
    return
  }

  parentOptions.value = []
}

// 生成机构编码（ORG + 时间戳）
const generateOrganizationCode = () => {
  const timestamp = Date.now()
  return `ORG${timestamp}`
}

const handleAdd = () => {
  editingRecord.value = null
  formData.value = {
    code: generateOrganizationCode(),
    name: '',
    level: '',
    parent: undefined,
    manager: '',
    date: null,
    status: '启用',
  }
  visible.value = true
  fetchAllOrganizationOptions().then(() => {
    updateParentOptions()
  })
}

const handleEdit = (record) => {
  editingRecord.value = record
  formData.value = {
    code: record.code || '',
    name: record.name || '',
    level: record.level || '',
    parent: record.parent || record.parentCode || undefined,
    manager: record.manager || '',
    date: record.date ? (typeof record.date === 'string' ? dayjs(record.date) : record.date) : null,
    status: record.status || '启用',
  }
  visible.value = true
  fetchAllOrganizationOptions().then(() => {
    updateParentOptions()
  })
}

const handleDelete = async (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除机构"${record.name}"吗？`,
    async onOk() {
      try {
        await deleteOrganization(record.id)
        message.success('删除成功')
        fetchOrganizationList() // 重新获取列表数据
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败，请稍后重试')
      }
    },
  })
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch (error) {
    // 验证失败，不继续执行
    if (error?.errorFields) {
      return
    }
  }

  try {
    confirmLoading.value = true

    if (editingRecord.value) {
      // 编辑机构 - 不包含code字段（code不可修改）
      const updateData = {
        name: formData.value.name,
      }

      // 只添加有值的字段，避免传递 undefined
      if (formData.value.level) {
        updateData.level = formData.value.level
      }
      if (formData.value.parent) {
        updateData.parentCode = formData.value.parent
      }
      if (formData.value.manager) {
        updateData.manager = formData.value.manager
      }
      if (formData.value.date) {
        updateData.date =
          typeof formData.value.date === 'string'
            ? formData.value.date
            : formData.value.date.format('YYYY-MM-DD')
      }
      if (formData.value.status) {
        updateData.status = formData.value.status
      }

      await updateOrganization(editingRecord.value.id, updateData)
      message.success('修改成功')
    } else {
      // 新增机构
      const submitData = {
        code: formData.value.code,
        name: formData.value.name,
        level: formData.value.level,
        parentCode: formData.value.parent || undefined,
        manager: formData.value.manager || undefined,
        date: formData.value.date
          ? typeof formData.value.date === 'string'
            ? formData.value.date
            : formData.value.date.format('YYYY-MM-DD')
          : undefined,
        status: formData.value.status || '启用',
      }
      await createOrganization(submitData)
      message.success('新增成功')
    }

    visible.value = false

    // 重新获取列表数据
    fetchOrganizationList()
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败，请稍后重试')
  } finally {
    confirmLoading.value = false
  }
}

const handleSearch = () => {
  fetchOrganizationList()
}

onMounted(() => {
  fetchOrganizationList()
  fetchAllOrganizationOptions()
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">机构关系设置</h1>
      <p class="page-desc">设置一级机构、二级机构、三级机构以及机构间从属关系</p>
    </div>

    <div class="page-content">
      <div class="toolbar">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索机构名称或编码"
          style="width: 300px"
          allow-clear
          @search="handleSearch"
          @clear="handleSearch"
        />
        <a-button type="primary" @click="handleAdd">
          <template #icon>➕</template>
          新增机构
        </a-button>
      </div>

      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="{ pageSize: 10 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" size="small" danger @click="handleDelete(record)"
                >删除</a-button
              >
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal
      v-model:open="visible"
      :title="editingRecord ? '编辑机构' : '新增机构'"
      width="600px"
      :confirm-loading="confirmLoading"
      @ok="handleSubmit"
      @cancel="
        () => {
          visible = false
        }
      "
    >
      <a-form ref="formRef" :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item
          label="机构编码"
          name="code"
          :rules="[{ required: true, message: '请输入机构编码' }]"
        >
          <a-input
            v-model:value="formData.code"
            placeholder="系统自动生成"
            :disabled="!!editingRecord"
            readonly
            style="background-color: #f5f5f5; cursor: not-allowed"
          />
        </a-form-item>
        <a-form-item
          label="机构名称"
          name="name"
          :rules="[{ required: true, message: '请输入机构名称' }]"
        >
          <a-input v-model:value="formData.name" placeholder="请输入机构名称" />
        </a-form-item>
        <a-form-item
          label="机构级别"
          name="level"
          :rules="[{ required: true, message: '请选择机构级别' }]"
        >
          <a-select
            v-model:value="formData.level"
            placeholder="请选择机构级别"
            @change="
              () => {
                formData.parent = undefined
                updateParentOptions()
              }
            "
          >
            <a-select-option value="一级机构">一级机构</a-select-option>
            <a-select-option value="二级机构">二级机构</a-select-option>
            <a-select-option value="三级机构">三级机构</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="上级机构" name="parent">
          <a-select
            v-model:value="formData.parent"
            placeholder="请选择上级机构"
            :disabled="formData.level === '一级机构'"
            allow-clear
          >
            <a-select-option
              v-for="option in parentOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="负责人" name="manager">
          <a-input v-model:value="formData.manager" placeholder="请输入负责人" />
        </a-form-item>
        <a-form-item label="成立日期" name="date">
          <a-date-picker v-model:value="formData.date" style="width: 100%" />
        </a-form-item>
        <a-form-item
          label="状态"
          name="status"
          :rules="[{ required: true, message: '请选择状态' }]"
        >
          <a-select v-model:value="formData.status" placeholder="请选择状态">
            <a-select-option value="启用">启用</a-select-option>
            <a-select-option value="停用">停用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}
</style>
